<?php
namespace Rainrock\Framework\Controller;


use Rainrock\Framework\kernel\core\Controller;
use Rainrock\Framework\kernel\core\Module;
use Rainrock\Framework\kernel\base\Rock;


/**
*	计划任务运行使用5分钟运行一次
*/
class SystaskController extends Controller{
	
	private $taskmodel;
	
	public function indexAction()
	{
		$mode = Module::get('systask', 'system');
		if(!$mode)return 'not install systask';
		
		if(PHP_SAPI != 'cli'){
			
			$cont   = '@echo off'.chr(10).'';
			$cont  .= 'php "'.ROOT_PATH.'/index.php" systask';
			$file   = Rock::createFile('webstatic/systemtask.bat', $cont, ROOT_PATH);
			$str 	= 'schtasks /create /sc DAILY /mo 1 /du "24:00" /ri 5 /sd "2017/04/01" /st "00:00:05" /tn "'.TITLE.'计划任务" /ru System /tr '.str_replace('/','\\', ROOT_PATH).'\webstatic\systemtask.bat';
			return '安装方法：<br>'.$str.'';
		}
		
		
		$this->taskmodel = $mode->getModel();
		$rows = $this->taskmodel->getall('`status`=1');
		$runci = 0;
		$succi = 0;
		$errci = 0;
		foreach($rows as $k=>$rs){
			$result = $this->runTask($rs);
			if($result != 'wait'){
				$runci++;
				if($this->isempt($result)){
					$errci++;
				}else{
					$succi++;
				}
				$this->taskmodel->update(array(
					'lastdt' => Rock::now(),
					'result' => $result
				),$rs['id']);
			}
		}
		return 'task('.$runci.'),success('.$succi.'),error('.$errci.')';
	}
	
	//运行计划任务5分钟内
	private function runTask($rs)
	{
		$stime   = strtotime(date('Y-m-d H:i:00'));
		$vtime   = $stime % 300;
		$stime	 = $stime - $vtime;
		$runtime = $this->getruntime($rs['runtime'], $stime, $stime+299);//运行时间
		if($runtime){
			return $this->runTaskurl($rs['runurl']);//运行地址
		}else{
			return 'wait';
		}
	}
	
	//运行地址
	private function runTaskurl($url)
	{
		if(substr($url,0,4)=='http'){
			return $this->c('curl')->getcurl($url);
		}else{
			$arr  = explode(',', $url);
			$mode = $arr[0];
			$act  = Rock::arrvalue($arr, 1, 'run');
			$can  = Rock::arrvalue($arr, 2);
			$obj  = $this->c($mode);
			if(method_exists($obj, $act)){
				return $obj->$act($can);
			}else{
				return 'not dev('.$url.')';
			}
		}
	}
	
	//获取运行时间
	private function getruntime($time, $stime, $ntime)
	{
		$type  = 'd';
		$jg    = 1;
		$shi   = $time;
		if($this->contain($time,',')){
			$arr = explode(',', $time);
			$type= $arr[0];
			$shi = $arr[1];
			if(strlen($type)>1){
				$jg = (int)substr($type, 1);
			}
		}
		$str = '';
		if($type=='d'){
			$str = date('Y-m-d '.$shi.'');
		}
		if($str){
			$otime = strtotime($str);
			if($otime >= $stime && $otime <= $ntime){
			}else{
				$str = '';
			}
		}
		return $str;
	}
}